﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace HotShot.Entities
{
    public static class EntityBaseExtender
    {
        static object locker = new object();
        static List<Type> _knownTypes = new List<Type>();
        static XmlSerializer _serializer;

        static EntityBaseExtender()
        {
            Init(new List<Type>());
        }

        public static void Init(List<Type> knownTypes)
        {
            knownTypes.Add(typeof(EntityBase));
            knownTypes.AddRange(_knownTypes);
            knownTypes = knownTypes.Distinct().ToList();
            lock (locker)
            {
                _knownTypes = knownTypes;
                _serializer = new XmlSerializer(typeof(object), knownTypes.ToArray());
            }
        }

        public static string ToXml(this object e)
        {
            StringBuilder sb = new StringBuilder();
            XmlWriter w = XmlWriter.Create(sb);
            _serializer.Serialize(w, e);
            w.Flush();
            return sb.ToString();
        }

        public static T FromXml<T>(this string xml) where T : class
        {
            TextReader s = new StringReader(xml);
            XmlReader r = XmlReader.Create(s);
            var result = _serializer.Deserialize(r) as T;
            return result;
        }
    }
}
